package com.hongkuncheng.cms.controller.admin;

import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.Properties;
import com.hongkuncheng.cms.helper.*;
import com.hongkuncheng.cms.model.*;
import org.hibernate.Criteria;
import org.hibernate.sql.JoinType;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Transactional
@RequestMapping("admin")
public class AindexController extends BaseController {

    // 主页
    @RequestMapping
    public String index() {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if (admin == null) {
            print("admin is empty!");
            return null;
        }
        request.setAttribute("fromlogin", request.getHeader("Referer") == null ? false :
                request.getHeader("Referer").endsWith("/admin/login"));
        return request.getRequestURI().endsWith("/") ? view() : "redirect:/admin/";
    }

    // 顶部
    @RequestMapping("top")
    public String top() {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        admin = factorySession.get(Admin.class, admin.getId());
        request.setAttribute("admin", admin);
        return view();
    }

    // 左侧
    @RequestMapping("left")
    public String left() {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        admin = factorySession.get(Admin.class, admin.getId());
        request.setAttribute("admin", admin);
        request.setAttribute("ismaster", Boolean.parseBoolean(applicationIsMaster));
        // 栏目集合
        List<Columns> columnses = new ArrayList<Columns>();
        List<Columns> columnsForZhuanties = new ArrayList<Columns>();
        List<Zhuanti> zhuantis = new ArrayList<Zhuanti>();
        List<Integer> zhuantiIds = new ArrayList<Integer>();
        List<Columns> columns1es = factorySession.createCriteria(Columns.class)
                .add(Restrictions.eq("parentId", 0))
                .addOrder(Order.asc("sort")).list();
        for (Columns columns1 : columns1es) {
            List<Columns> columns2Temp = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("columnsType.id", 1))
                    .add(Restrictions.eq("parentId", columns1.getId()))
                    .addOrder(Order.asc("sort")).list();
            if (columns1.getColumnsType().getId() == 1 || columns2Temp.size() > 0)
                columnses.add(columns1);
            if (columns2Temp.size() > 0)
                for (Columns columns2 : columns2Temp) columnses.add(columns2);
            if (columns1.getColumnsType().getId() == 6) {
                if (!zhuantiIds.contains(columns1.getZhuanti().getId())) {
                    zhuantis.add(columns1.getZhuanti());
                    zhuantiIds.add(columns1.getZhuanti().getId());
                }
                columnsForZhuanties.add(columns1);
            }
        }
        request.setAttribute("columnses", columnses);
        request.setAttribute("zhuantis", zhuantis);
        request.setAttribute("columnsForZhuanties", columnsForZhuanties);
        List<Form> forms = factorySession.createCriteria(Form.class).addOrder(Order.asc("sort")).list();
        request.setAttribute("forms", forms);
        return view();
    }

    // 欢迎
    @RequestMapping("welcome")
    public String welcome() {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        admin = factorySession.get(Admin.class, admin.getId());
        request.setAttribute("admin", admin);
        Properties props = System.getProperties();
        request.setAttribute("systemInfo", props.getProperty("os.name") + " " + props.getProperty("os.version") +
                " JDK" + System.getProperty("java.version"));
        Criteria criterArticle = factorySession.createCriteria(Article.class, "this_")
                .createAlias("checknode", "article_checknode", JoinType.LEFT_OUTER_JOIN)
                .createAlias("article_checknode.checknodeReAdmins", "cnra", JoinType.LEFT_OUTER_JOIN)
                .createAlias("cnra.checknode", "cnra_checknode")
                .add(Restrictions.eq("cnra_checknode.checknodeType.id", 2))
                .add(Restrictions.eq("cnra.admin.id", admin.getId()));
        String title = request.getParameter("title");
        if (title != null) criterArticle.add(Restrictions.like("title", title, MatchMode.ANYWHERE));
        request.setAttribute("title", title);
        List<Article> articleTemps = criterArticle.list(); // 临时数据集合
        int waitecheckArticleCount = 0; // 待审核文档数量
        for (Article article : articleTemps) {
            if (article.getChecknode().isGroupbydepart())
                if (article.getAdmin().getDepartment().getId() != admin.getDepartment().getId())
                    continue;
            if (!article.getChecknode().isSingleaudit()) {
                // 会审
                // 获取审核记录集里和当前节点不同的最大ID值
                Object uniqueResult = factorySession.createCriteria(Checkrecord.class)
                        .add(Restrictions.eq("article.id", article.getId()))
                        .add(Restrictions.or(Restrictions.and(Restrictions.isNotNull("checknode"),
                                Restrictions.ne("checknode.id", article.getChecknode().getId())),
                                Restrictions.and(Restrictions.isNull("checknode"),
                                        Restrictions.eq("checkrecordResult.id", 3))))
                        .setProjection(Projections.max("id")).uniqueResult();
                int neqmaxId = uniqueResult == null ? 0 : Integer.parseInt(uniqueResult.toString());
                // 获取当前文档当前审核节点已经参与审核的人员数（限当前用户），用于验证已会审人员是否包含当前用户
                uniqueResult = factorySession.createCriteria(Checkrecord.class)
                        .add(Restrictions.gt("id", neqmaxId))
                        .add(Restrictions.eq("article.id", article.getId()))
                        .add(Restrictions.eq("checknode.id", article.getChecknode().getId()))
                        .add(Restrictions.eq("admin.id", admin.getId()))
                        .setProjection(Projections.count("id"))
                        .setProjection(Projections.countDistinct("id"))
                        .uniqueResult();
                if (uniqueResult == null || Integer.parseInt(uniqueResult.toString()) == 0) waitecheckArticleCount++;
            } else {
                waitecheckArticleCount++;
            }
        }
        request.setAttribute("waitecheckArticleCount", waitecheckArticleCount);
        // 其它单位报送过来的文档数量
        int orgpushArticleCount = 0;
        if (AdminHelper.checkAdminPermission(admin, "office_article_receive"))
            orgpushArticleCount = Integer.parseInt(factorySession.createCriteria(ArticlePush.class)
                    .setProjection(Projections.countDistinct("id"))
                    .uniqueResult().toString());
        request.setAttribute("orgpushArticleCount", orgpushArticleCount);
        List<Integer> formIds = new ArrayList<Integer>();
        for (AdminReAdminRole arar : admin.getAdminReAdminRoles()) {
            AdminRole adminrole = arar.getAdminRole();
            if (AdminHelper.checkAdminPermission(admin, "business_form_")) formIds.add(adminrole.getId());
        }
        // 等待处理的表单
        int waitecheckFormCount = 0;
        int waitecheckFormId = 0;
        if (formIds.size() > 0) {
            List<Form> forms = factorySession.createCriteria(Form.class)
                    .createAlias("formDatas", "formData", JoinType.LEFT_OUTER_JOIN)
                    .add(Restrictions.in("id", formIds))
                    .add(Restrictions.isNull("formData.result")).list();
            waitecheckFormCount = forms.size();
            if (waitecheckFormCount > 0) waitecheckFormId = forms.get(0).getId();
        }
        request.setAttribute("waitecheckFormCount", waitecheckFormCount);
        request.setAttribute("waitecheckFormId", waitecheckFormId);
        // 等待处理的留言
        int waitecheckLmgCount = 0;
        if (AdminHelper.checkAdminPermission(admin, "business_leavemessage_manage"))
            waitecheckLmgCount = Integer.parseInt(factorySession.createCriteria(Leavemessage.class)
                    .add(Restrictions.eq("checked", false))
                    .setProjection(Projections.countDistinct("id"))
                    .uniqueResult().toString());
        request.setAttribute("waitecheckLmgCount", waitecheckLmgCount);
        List<Notice> notices = factorySession.createCriteria(Notice.class)
                .add(Restrictions.eq("admin.id", admin.getId()))
                .list();
        request.setAttribute("notices", notices);
        // 是否从登录页面过来
        boolean fromlogin = Boolean.parseBoolean(request.getParameter("fromlogin"));
        if (fromlogin && admin.getPassword().equals(SecurityHelper.md5Encrypt(admin.getAccount() + "_123456"))) {
            request.setAttribute("message", "安全提示：\\n系统检测到您的密码为初始化默认密码，\\n为了您的数据安全，" +
                    "建议您尽快修改密码。");
        }
        return view();
    }

    // 登录
    @RequestMapping("login")
    public String login() {
        String account = CookieHelper.GetCookie(request, "account", true);
        if (account != null && !account.isEmpty()) request.setAttribute("account", account);
        return view();
    }

    // 单点登录
    @RequestMapping("loginSingle")
    public void loginSingle() {
        Admin admin = factorySession.get(Admin.class, 1);
        request.getSession().setAttribute("admin", admin);
        request.getSession().setAttribute("windowheight", Integer.parseInt(request.getParameter("windowheight")));
        request.getSession().setAttribute("editorpath", "admin/" + admin.getId());
        request.getSession().setAttribute("watermark", factorySession.get(Watermark.class, 1));
        try {
            response.sendRedirect("/admin/");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 登录处理
    @RequestMapping("logindo")
    @ResponseBody
    public void logindo() throws Exception {
        String checkcode = CookieHelper.GetCookie(request, "checkcode", true);
        if (checkcode == null) {
            PageHelper.alertAndRedirect("验证码加载失败", "login");
        } else {
            String vcode = request.getParameter("vcode");
            if (!vcode.equalsIgnoreCase(checkcode)) {
                PageHelper.alertAndGoBack("验证码错误，请重新输入。");
            } else {
                String account = request.getParameter("account");
                String password = request.getParameter("password");
                if (account == null || password == null) {
                    response.sendRedirect("/errors/500.html");
                } else {
                    Object uniqueResult = factorySession.createCriteria(Admin.class)
                            .add(Restrictions.eq("account", account))
                            .add(Restrictions.eq("password", SecurityHelper.md5Encrypt(account + "_" + password)))
                            .uniqueResult();
                    if (uniqueResult != null) {
                        Admin admin = (Admin) uniqueResult;
                        request.getSession().setAttribute("admin", admin);
                        request.getSession().setAttribute("windowheight", request.getParameter("windowheight"));
                        request.getSession().setAttribute("editorpath", "admin/" + admin.getId());
                        request.getSession().setAttribute("watermark", factorySession.get(Watermark.class, 1));
                        CookieHelper.SetCookie(response, "account", account, 604800, true);
                        recordLog("登录系统");
                        response.sendRedirect("./");
                    } else {
                        PageHelper.alertAndGoBack("账号或密码错误，请重新输入。");
                    }
                }
            }
            CookieHelper.RemoveCookie(response, "checkcode");
        }
    }

    // 退出
    @RequestMapping("logout")
    @ResponseBody
    public void logout() {
        recordLog("退出系统");
        request.getSession().invalidate();
        PageHelper.redirectToTop("login");
    }

}
